package com.share.finance.risk.third.aop;

import com.alibaba.fastjson.JSONPath;
import com.share.config.redis.RedisClient;
import com.share.finance.risk.common.model.sys.ThirdRequest;
import com.share.finance.risk.third.model.db.InterfaceConfig;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Component
public class CacheApiData {
    @Autowired
    private RedisClient redisClient;

    public String getCacheKey(ThirdRequest thirdRequest, InterfaceConfig configPo) {
        if (StringUtils.isEmpty(configPo.getRedisKeys())) {
            return null;
        }
        List<String> redisKeys = Arrays.asList(configPo.getRedisKeys().split(","));
        StringBuffer sbf = new StringBuffer();
        sbf.append("third:" + configPo.getIntId() + ":");
        int delIndex = sbf.length();
        redisKeys.forEach(redisKey -> {
            sbf.append("-");
            sbf.append(JSONPath.eval(thirdRequest, redisKey));
        });
        sbf.deleteCharAt(delIndex);
        return sbf.toString();
    }

    /**
     * 调用数据源前置处理
     *
     * @return
     */
    public String getDataFromCache(ThirdRequest thirdRequest, InterfaceConfig configPo) {
        if (StringUtils.isBlank(configPo.getRedisKeys())) {
            return null;
        }

        String cacheKey = getCacheKey(thirdRequest, configPo);

        return redisClient.get(cacheKey);
    }

    /**
     * 调用数据源后置处理
     *
     * @param configPo
     * @param result
     * @return
     */
    public boolean setDataToCache(ThirdRequest thirdRequest, InterfaceConfig configPo, String result) {
        boolean isSuccess = false;
        if (StringUtils.isBlank(configPo.getRedisKeys()) || StringUtils.isBlank(result)) {
            isSuccess = false;
        } else {
            String[] values = Optional.ofNullable(configPo.getSucessValues()).orElse("").split(",");
            List<String> successValueList = Arrays.stream(values).map(m -> m.trim()).filter(f -> StringUtils.isNotBlank(f)).collect(Collectors.toList());
            Object eval = JSONPath.eval(result, configPo.getSucessFlag());
            String successCode = eval == null ? null : eval.toString();
            if (successValueList.contains(successCode)) {
                String cacheKey = getCacheKey(thirdRequest, configPo);
                if (StringUtils.isNotBlank(cacheKey)) {
                    //缓存单位默认是小时
                    long redisExpireTime = configPo.getRedisPeriod() != null ? configPo.getRedisPeriod() * 3600L : 3600L;
                    redisClient.set(cacheKey, result, redisExpireTime);
                    isSuccess = true;
                }
            }
        }
        return isSuccess;
    }
}
